<?php

namespace app\api\controller;

use app\admin\model\AskForLeave;
use app\admin\model\Club;
use app\admin\model\ClubDtl;
use app\admin\model\CustomerService;
use app\admin\model\Notice;
use app\admin\model\SearchShool;
use app\admin\model\Sharpshooter;
use app\admin\model\Tag;
use app\admin\model\TeacherArea;
use app\admin\model\TeacherClass;
use app\admin\model\TeacherClassDtl;
use app\admin\model\TeacherCollection;
use app\admin\model\TeacherDetail;
use app\admin\model\Withdraw;
use app\common\controller\Api;
use app\common\library\Getui;
use app\common\model\Test;
use app\common\model\WlqTest;
use think\Config;
use think\Db;
use think\Log;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    public function home(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        $data= [];
        //主社团
        $club = Club::field('id,name,img_url')->order('sort','asc')->select();
        $data['club'] = $club;

        $premium = \app\admin\model\IdentityInfo::where(['is_premium'=>1])->select();
        if($premium){
            $data['is_premium'] = 1;
            $data['premium'] = '精品课程';
            $data['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
        }else{
            $data['is_premium'] = 0;
            $data['premium'] = '精品课程';
            $data['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
        }
        
        // 获取当前登录用户（如果已登录）
        $current_user_id = null;
        try {
            $current_user = $this->auth->getUser();
            if (isset($current_user['id']) && $current_user['id']) {
                $current_user_id = $current_user['id'];
            }
        } catch (\Exception $e) {
            // 用户未登录，忽略
        }
        //优惠好课
        // 先查出隐藏的课程（detail_status=2）对应的teacher_detail_id
        $hidden_teacher_detail_ids = TeacherDetail::where(['detail_status'=>2])->column('id');

        // 先查出隐藏的教师（main_status=2）对应的info_id，然后找出这些教师对应的所有teacher_detail_id
        $hidden_info_ids = \app\admin\model\IdentityInfo::where(['identity_type'=>'教师','main_status'=>2])->column('id');
        $hidden_teacher_detail_ids_by_teacher = [];
        if (!empty($hidden_info_ids)) {
            $hidden_teacher_detail_ids_by_teacher = TeacherDetail::whereIn('info_id', $hidden_info_ids)->column('id');
        }

        // 合并所有需要排除的teacher_detail_id
        $exclude_teacher_detail_ids = array_unique(array_merge($hidden_teacher_detail_ids, $hidden_teacher_detail_ids_by_teacher));

        // 排除隐藏的课程和教师对应的sharpshooter
        $sharpshooter_query = Sharpshooter::with(['user','club_dtl']);
        if (!empty($exclude_teacher_detail_ids)) {
            $sharpshooter_query->whereNotIn('fa_sharpshooter.teacher_detail_id', $exclude_teacher_detail_ids);
        }
        $sharpshooter_model = $sharpshooter_query->order('sort','desc')->select();

        $sharpshooter = [];
        foreach ($sharpshooter_model as $k=>$v){
            $sharpshooter[$k]['id'] = $v['id'];
            $sharpshooter[$k]['user_id'] = $v['user_id'];
//            $sharpshooter[$k]['money'] = $v['money'];
            $sharpshooter[$k]['describe'] = $v['describe'];
            $sharpshooter[$k]['title'] = $v['title'];
//            $sharpshooter[$k]['teacher_detail_id'] = $v['teacher_detail_id'];
            $sharpshooter[$k]['nickname'] = $v['user']['nickname'];
            $sharpshooter[$k]['avatar'] = $v['user']['avatar'];
            $sharpshooter[$k]['club_two_name'] = isset($v['club_dtl']['name']) ? $v['club_dtl']['name'] ? $v['club_dtl']['name'] : '' : '';
            $remark = str_replace("，", ",", $v['remark']);
            $sharpshooter[$k]['remark'] = explode(',',$remark);

            $s_t = \app\admin\model\IdentityInfo::where(['user_id'=>$v['user_id'],'identity_type'=>'教师'])->find();
            $sharpshooter[$k]['teacher_detail_id'] = isset($s_t['id']) ? $s_t['id'] : '';

            if($s_t){
                $area = $s_t['area'] ? explode(',',$s_t['area']) : [];
            }else{
                $area = [];
            }
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $sharpshooter[$k]['money'] = isset($s_t['lowest_hourly_rate']) ? $s_t['lowest_hourly_rate'] : '';
            $sharpshooter[$k]['area_name'] = trim($area_name,',');
        }
        $data['sharpshooter'] = $sharpshooter;
        //教师
        $query_res = \app\admin\model\IdentityInfo::hasWhere('teacherDetail',function ($query)use($params){
            // 只显示状态为1的课程
            $query->where(['fa_teacher_detail.detail_status'=>1]);
            if(isset($params['club_one_id'])&&$params['club_one_id']){
                $query->where(['fa_teacher_detail.club_one_id'=>$params['club_one_id']]);
            }
            if(isset($params['club_two_id'])&&$params['club_two_id']){
                $query->where(['fa_teacher_detail.club_two_id'=>$params['club_two_id']]);
            }

            //工作经验
            if(isset($params['work_time'])&&$params['work_time']){
                switch ($params['work_time']){
                    case 1:
                        $work_time_sql = "work_time < 1";
                        break;
                    case 2:
                        $work_time_sql = "work_time >= 1 and work_time < 3";
                        break;
                    case 3:
                        $work_time_sql = "work_time >= 3 and work_time < 5";
                        break;
                    case 4:
                        $work_time_sql = "work_time >= 5 and work_time < 7";
                        break;
                    case 5:
                        $work_time_sql = "work_time >= 7 and work_time < 10";
                        break;
                    case 6:
                        $work_time_sql = "work_time >= 10 and work_time < 20";
                        break;
                    case 7:
                        $work_time_sql = "work_time >= 20 and work_time < 30";
                        break;
                    case 8:
                        $work_time_sql = "work_time >= 30";
                        break;
                    default:
                        $work_time_sql = '';
                        break;
                }
                if($work_time_sql){
                    $query->where($work_time_sql);
                }
            }
        });
        $query_res->with(['user','teacherDetail'=>function($query){
            // 只显示状态为1的课程
            $query->where(['detail_status'=>1]);
        }])->where(['identity_type'=>'教师','main_status'=>1]);

        //社团课程筛选
//        if(isset($params['club_one_id'])&&$params['club_one_id']){
//            $query_res->hasWhere('teacherDetail',['club_one_id'=>$params['club_one_id']]);
//        }
//        if(isset($params['club_two_id'])&&$params['club_two_id']){
//            $query_res->hasWhere('teacherDetail',['club_two_id'=>$params['club_two_id']]);
//        }
        //地区
        if(isset($params['area'])&&$params['area']){
            $query_res->whereRaw("FIND_IN_SET({$params['area']}, area) > 0");
        }
        //标签
        if(isset($params['tag'])&&$params['tag']){
            $query_res->whereRaw("FIND_IN_SET({$params['tag']}, tag) > 0");
        }
        //可约时间
        if(isset($params['appointment_time'])&&$params['appointment_time']){
            $appointmentTime = trim($params['appointment_time']);
            $query_time = null;
            if (preg_match('/^\d{1,2}:\d{1,2}(?::\d{1,2})?$/', $appointmentTime)) {
                $parts = explode(':', $appointmentTime);
                $hour = str_pad($parts[0], 2, '0', STR_PAD_LEFT);
                $minute = str_pad($parts[1] ?? '00', 2, '0', STR_PAD_LEFT);
                $second = str_pad($parts[2] ?? '00', 2, '0', STR_PAD_LEFT);
                $query_time = "{$hour}:{$minute}:{$second}";
            } else {
                $timestamp = strtotime($appointmentTime);
                if ($timestamp !== false) {
                    $query_time = date('H:i:s', $timestamp);
                }
            }
            if ($query_time) {
                $query_res->whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) <= '{$query_time}' AND 
    TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) >= '{$query_time}')");
            }
        }
        //最高学历
        if(isset($params['education_background'])&&$params['education_background']){
            $query_res->where('fa_identity_info.education_background',$params['education_background']);
        }
        //金额
        if(isset($params['price'])&&$params['price']){
            switch ($params['price']){
                case 1:
                    $hourly_rate_sql = "lowest_hourly_rate < 200";
                    break;
                case 2:
                    $hourly_rate_sql = "lowest_hourly_rate >= 200 and lowest_hourly_rate < 300";
                    break;
                case 3:
                    $hourly_rate_sql = "lowest_hourly_rate >= 300 and lowest_hourly_rate < 400";
                    break;
                case 4:
                    $hourly_rate_sql = "lowest_hourly_rate >= 400 and lowest_hourly_rate < 500";
                    break;
                case 5:
                    $hourly_rate_sql = "lowest_hourly_rate >= 500 and lowest_hourly_rate < 700";
                    break;
                case 6:
                    $hourly_rate_sql = "lowest_hourly_rate >= 700 and lowest_hourly_rate < 1000";
                    break;
                case 7:
                    $hourly_rate_sql = "lowest_hourly_rate >= 1000 and lowest_hourly_rate < 2000";
                    break;
                case 8:
                    $hourly_rate_sql = "lowest_hourly_rate >= 2000";
                    break;
                default:
                    $hourly_rate_sql = '';
                    break;
            }
            if($hourly_rate_sql){
                $query_res->where($hourly_rate_sql);
            }
        }
        //性别
        if(isset($params['gender'])&&$params['gender']){
            if($params['gender'] == 1){
                $gender_user_id_arr = \app\admin\model\User::where(['gender'=>1])->column('id');
                $query_res->whereIn('user_id',$gender_user_id_arr);
            }
            if($params['gender'] == 2){
                $gender_user_id_arr = \app\admin\model\User::where(['gender'=>0])->column('id');
                $query_res->whereIn('user_id',$gender_user_id_arr);
            }
        }
        $query_res->where("lowest_hourly_rate > 0");
        if(isset($params['area_sort'])&&$params['area_sort']){
            //当前地址地区排序 - 包含传入值的排在最前面，其他按order_num排序
            $area_sort = (int)$params['area_sort']; // 转换为整数防止SQL注入
            $query_res = $query_res->orderRaw("FIND_IN_SET({$area_sort}, area)>0 DESC");
        }

        if(isset($params['sort_type'])&&$params['sort_type']){
            if($params['sort_type']!='desc'&&$params['sort_type']!='asc'&&$params['sort_type']!='DESC'&&$params['sort_type']!='ASC'){
                $this->error('排序方式参数错误');
            }
        }
        if(isset($params['sort_name'])&&$params['sort_name']){
            switch ($params['sort_name']){
                case "score":
                    if(isset($params['sort_type'])&&$params['sort_type']){
                        $query_res = $query_res->order('main_score',$params['sort_type']);
                    }else{
                        $query_res = $query_res->order('main_score','desc');
                    }
                    break;
                case "price":
                    if(isset($params['sort_type'])&&$params['sort_type']) {
                        $query_res = $query_res->order('lowest_hourly_rate',$params['sort_type']);
                    }else{
                        $query_res = $query_res->order('lowest_hourly_rate', 'desc');
                    }
                    break;
                default:
                    break;
            }
        }

        $query_res = $query_res->order('main_people','desc');
        $query_res = $query_res->paginate($params['page_size']);

        $list = $query_res->getCollection();

        // 获取当前登录用户（如果已登录）
        $current_user_id = null;
        try {
            $current_user = $this->auth->getUser();
            if (isset($current_user['id']) && $current_user['id']) {
                $current_user_id = $current_user['id'];
            }
        } catch (\Exception $e) {
            // 用户未登录，忽略
        }

        // 如果用户已登录，批量查询收藏状态
        $collected_teacher_detail_ids = [];
        if ($current_user_id) {
            // 收集所有teacher_detail_id
            $all_teacher_detail_ids = [];
            foreach ($list as $v) {
                foreach ($v['teacher_detail'] as $vv) {
                    if (isset($vv['id'])) {
                        $all_teacher_detail_ids[] = $vv['id'];
                    }
                }
            }
            // 批量查询收藏状态
            if (!empty($all_teacher_detail_ids)) {
                $collected_teacher_detail_ids = TeacherCollection::where(['user_id' => $current_user_id])
                    ->whereIn('teacher_detail_id', array_unique($all_teacher_detail_ids))
                    ->column('teacher_detail_id');
            }
        }

        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = $v['user_id'];
            $arr[$k]['name']     = $v['name'];
            $club_dtl_name = [];
            $teacher_detail = [];
            foreach ($v['teacher_detail'] as $kk=>$vv){
                if(isset($vv['club_dtl_s']['name'])&&$vv['club_dtl_s']['name']){
                    $club_dtl_name[] = $vv['club_dtl_s']['name'];
                }
                $teacher_detail[$kk]['id'] = $vv['id'];
                $teacher_detail[$kk]['info_id'] = $vv['info_id'];
                $teacher_detail[$kk]['hourly_rate'] = $vv['hourly_rate'];
                $teacher_detail[$kk]['club_name'] = isset($vv['club_dtl_s']['name']) ? $vv['club_dtl_s']['name'] : '';
                $teacher_detail[$kk]['club_img_url'] = isset($vv['club_dtl_s']['img_url']) ? $vv['club_dtl_s']['img_url'] : '';
                $teacher_detail[$kk]['is_premium'] = $vv['is_premium'];
                $teacher_detail[$kk]['people'] = $vv['people'];
                if($vv['work_time']>0){
                    $teacher_detail[$kk]['work_time'] = $vv['work_time'].'年';
                }else{
                    $teacher_detail[$kk]['work_time'] = '';
                }
                // 检查该课程是否被收藏
                $is_collected = 2; // 默认2=未收藏
                if ($current_user_id && isset($vv['id']) && in_array($vv['id'], $collected_teacher_detail_ids)) {
                    $is_collected = 1; // 1=已收藏
                }
                $teacher_detail[$kk]['is_collected'] = $is_collected; // 1已收藏，2未收藏
            }
            $club_dtl_name = array_values(array_unique($club_dtl_name));
            $arr[$k]['club_dtl_name'] = $club_dtl_name;
            $arr[$k]['hourly_rate']    = $v['lowest_hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['main_score']);
            $arr[$k]['people']    = $v['main_people'];
            $arr[$k]['order_num']    = $v['order_num_all'];
            $arr[$k]['education_background']    = $v['education_background'];
            $week = isset($v['appointment_time_week']) ? $v['appointment_time_week'] : '';
            $time = isset($v['appointment_time']) ? $v['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $arr[$k]['avatar']    = $v['user']['avatar'];

            $area = $v['area'] ? explode(',',$v['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
            $arr[$k]['dtl']    = $teacher_detail;
        }

        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;
        $this->success('首页',$data);
    }
    public function home_old_251109(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        $data= [];
        //主社团
        $club = Club::field('id,name,img_url')->order('sort','asc')->select();
        $data['club'] = $club;

        $premium = \app\admin\model\IdentityInfo::where(['is_premium'=>1])->select();
        if($premium){
            $data['is_premium'] = 1;
            $data['premium'] = '精品课程';
            $data['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
        }else{
            $data['is_premium'] = 0;
            $data['premium'] = '精品课程';
            $data['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
        }
        //神枪手
        $sharpshooter_model = Sharpshooter::with(['user','club_dtl'])->order('sort','desc')->select();
        $sharpshooter = [];
        foreach ($sharpshooter_model as $k=>$v){
            $sharpshooter[$k]['id'] = $v['id'];
            $sharpshooter[$k]['user_id'] = $v['user_id'];
            $sharpshooter[$k]['money'] = $v['money'];
            $sharpshooter[$k]['describe'] = $v['describe'];
            $sharpshooter[$k]['title'] = $v['title'];
            $sharpshooter[$k]['teacher_detail_id'] = $v['teacher_detail_id'];
            $sharpshooter[$k]['nickname'] = $v['user']['nickname'];
            $sharpshooter[$k]['avatar'] = $v['user']['avatar'];
            $sharpshooter[$k]['club_two_name'] = isset($v['club_dtl']['name']) ? $v['club_dtl']['name'] ? $v['club_dtl']['name'] : '' : '';
            $remark = str_replace("，", ",", $v['remark']);
            $sharpshooter[$k]['remark'] = explode(',',$remark);

            $s_t = \app\admin\model\IdentityInfo::where(['user_id'=>$v['user_id'],'identity_type'=>'教师'])->find();

            if($s_t){
                $area = $s_t['area'] ? explode(',',$s_t['area']) : [];
            }else{
                $area = [];
            }
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $sharpshooter[$k]['area_name'] = trim($area_name,',');
        }
        $data['sharpshooter'] = $sharpshooter;

        $tag = Tag::order('sort','desc')->select();
        $data['tag'] = $tag;

        $query_res = TeacherDetail::with(['identity','club_dtl'])->where('info_id > 0');
        //社团课程筛选
        if(isset($params['club_one_id'])&&$params['club_one_id']){
            $query_res->where(['club_one_id'=>$params['club_one_id']]);
        }
        if(isset($params['club_two_id'])&&$params['club_two_id']){
            $query_res->where(['club_two_id'=>$params['club_two_id']]);
        }
        //地区
        if(isset($params['area'])&&$params['area']){
            $query_res->whereRaw("FIND_IN_SET({$params['area']}, area) > 0");
        }
        //标签
        if(isset($params['tag'])&&$params['tag']){
            $query_res->whereRaw("FIND_IN_SET({$params['tag']}, tag) > 0");
        }
        //可约时间
        if(isset($params['appointment_time'])&&$params['appointment_time']){
            $info_time = \app\admin\model\IdentityInfo::whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) > '{$params['appointment_time']}' AND 
     TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) < '{$params['appointment_time']}')")->column('id');
            $query_res->whereIn('info_id',$info_time);
        }
        //工作经验
        if(isset($params['work_time'])&&$params['work_time']){
            switch ($params['work_time']){
                case 1:
                    $work_time_sql = "work_time < 1";
                    break;
                case 2:
                    $work_time_sql = "work_time >= 1 and work_time < 3";
                    break;
                case 3:
                    $work_time_sql = "work_time >= 3 and work_time < 5";
                    break;
                case 4:
                    $work_time_sql = "work_time >= 5 and work_time < 7";
                    break;
                case 5:
                    $work_time_sql = "work_time >= 7 and work_time < 10";
                    break;
                case 6:
                    $work_time_sql = "work_time >= 10 and work_time < 20";
                    break;
                case 7:
                    $work_time_sql = "work_time >= 20 and work_time < 30";
                    break;
                case 8:
                    $work_time_sql = "work_time >= 30";
                    break;
                default:
                    $work_time_sql = '';
                    break;
            }
            if($work_time_sql){
                $query_res->where($work_time_sql);
            }
        }
        //最高学历
        if(isset($params['education_background'])&&$params['education_background']){
            $education_background_arr_id = \app\admin\model\IdentityInfo::where(['education_background'=>$params['education_background']])->column('id');
            $query_res->whereIn('info_id',$education_background_arr_id);
        }
        //金额
        if(isset($params['price'])&&$params['price']){
            switch ($params['price']){
                case 1:
                    $hourly_rate_sql = "hourly_rate < 200";
                    break;
                case 2:
                    $hourly_rate_sql = "hourly_rate >= 200 and hourly_rate < 300";
                    break;
                case 3:
                    $hourly_rate_sql = "hourly_rate >= 300 and hourly_rate < 400";
                    break;
                case 4:
                    $hourly_rate_sql = "hourly_rate >= 400 and hourly_rate < 500";
                    break;
                case 5:
                    $hourly_rate_sql = "hourly_rate >= 500 and hourly_rate < 700";
                    break;
                case 6:
                    $hourly_rate_sql = "hourly_rate >= 700 and hourly_rate < 1000";
                    break;
                case 7:
                    $hourly_rate_sql = "hourly_rate >= 1000 and hourly_rate < 2000";
                    break;
                case 8:
                    $hourly_rate_sql = "hourly_rate >= 2000";
                    break;
                default:
                    $hourly_rate_sql = '';
                    break;
            }
            if($hourly_rate_sql){
                $query_res->where($hourly_rate_sql);
            }
        }
        //性别
        if(isset($params['gender'])&&$params['gender']){
            $gender_user_id_arr = \app\admin\model\User::where(['gender'=>$params['gender']])->column('id');
            $gender_info_id_arr = \app\admin\model\IdentityInfo::where(['identity_type'=>'教师'])->whereIn('user_id',$gender_user_id_arr)->column('id');
            $query_res->whereIn('info_id',$gender_info_id_arr);
        }

        //排序
        if(isset($params['score'])&&$params['score']){
            //评分排序
            $query_res = $query_res->order('score','desc')->order('order_num','desc');
        }else{
            if(isset($params['area_sort'])&&$params['area_sort']){
                //当前地址地区排序 - 包含传入值的排在最前面，其他按order_num排序
                $area_sort = (int)$params['area_sort']; // 转换为整数防止SQL注入
                $info_order = \app\admin\model\IdentityInfo::where(['identity_type'=>'教师'])->whereRaw("FIND_IN_SET({$area_sort}, area)")->column('id');
                
                // 使用FIELD函数让搜索出来的id对应的记录排在前面
                if (!empty($info_order)) {
                    // 过滤数组中的值，确保都是整数，防止SQL注入
                    $info_order = array_map('intval', $info_order);
                    $info_order_ids = implode(',', $info_order);
                    // FIELD(info_id, id1, id2, ...) DESC: 在列表中的返回位置(>0)排在前面，不在列表中的返回0排在后面
                    $query_res = $query_res->orderRaw("FIELD(info_id, {$info_order_ids}) DESC, order_num DESC,score DESC");
                } else {
                    // 如果没有匹配的，直接按order_num排序
                    $query_res = $query_res->order('order_num', 'desc')->order('score','desc');
                }
            }else{
                //订单排序
                $query_res = $query_res->order('order_num','desc')->order('score','desc');
            }
        }

        $query_res = $query_res->paginate($params['page_size']);
        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = isset($v['identity']['user_id']) ? $v['identity']['user_id'] : '';
            $arr[$k]['name']     = isset($v['identity']['name']) ? $v['identity']['name'] : '';
            $arr[$k]['club_dtl_name'] = isset($v['club_dtl']['name']) ? $v['club_dtl']['name'] : '';
            $arr[$k]['hourly_rate']    = $v['hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['score']);
            $arr[$k]['people']    = $v['people'];
            $arr[$k]['order_num']    = $v['order_num'];
            $arr[$k]['is_premium']    = $v['is_premium'];

            $week = isset($v['identity']['appointment_time_week']) ? $v['identity']['appointment_time_week'] : '';
            $time = isset($v['identity']['appointment_time']) ? $v['identity']['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $arr[$k]['avatar']    = isset($v['identity']['user']['avatar']) ? $v['identity']['user']['avatar'] : '';

            $area = $v['identity']['area'] ? explode(',',$v['identity']['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
        }
        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;
        $this->success('首页',$data);
    }
    public function home_old(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        $data= [];
        //主社团
        $club = Club::field('id,name,img_url')->order('sort','asc')->select();
        $data['club'] = $club;

        $premium = \app\admin\model\IdentityInfo::where(['is_premium'=>1])->select();
        if($premium){
            $data['is_premium'] = 1;
            $data['premium'] = '精品课程';
            $data['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
        }else{
            $data['is_premium'] = 0;
            $data['premium'] = '精品课程';
            $data['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
        }
        //社团为精品课程
//        $club_arr = [];
//        $dtl = ClubDtl::where(['is_premium'=>1])->order('sort','desc')->select();
//        if($dtl){
//            $club_arr[0]['id'] = '99995';
//            $club_arr[0]['name'] = '精品课程';
//            $club_arr[0]['img_url'] = '/uploads/20250831/6e5511975c0d84f4384741e35013353a.svg';
//            $asd = 1;
//        }else{
//            $asd = 0;
//        }
//        foreach ($club as $k=>$v){
//            $club_arr[$asd]['id'] = $v['id'];
//            $club_arr[$asd]['name'] = $v['name'];
//            $club_arr[$asd]['img_url'] = $v['img_url'];
//            $asd++;
//        }
//        $data['club'] = $club_arr;
        //神枪手
        $sharpshooter_model = Sharpshooter::with('user')->order('sort','desc')->select();
        $sharpshooter = [];
        foreach ($sharpshooter_model as $k=>$v){
            $sharpshooter[$k]['id'] = $v['id'];
            $sharpshooter[$k]['user_id'] = $v['user_id'];
            $sharpshooter[$k]['money'] = $v['money'];
            $sharpshooter[$k]['describe'] = $v['describe'];
            $sharpshooter[$k]['title'] = $v['title'];
            $sharpshooter[$k]['nickname'] = $v['user']['nickname'];
            $sharpshooter[$k]['avatar'] = $v['user']['avatar'];
            $remark = str_replace("，", ",", $v['remark']);
            $sharpshooter[$k]['remark'] = explode(',',$remark);

            $s_t = \app\admin\model\IdentityInfo::where(['user_id'=>$v['user_id'],'identity_type'=>'教师'])->find();

            if($s_t){
                $area = $s_t['area'] ? explode(',',$s_t['area']) : [];
            }else{
                $area = [];
            }
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $sharpshooter[$k]['area_name'] = trim($area_name,',');
        }
        $data['sharpshooter'] = $sharpshooter;

        $tag = Tag::order('sort','desc')->select();
        $data['tag'] = $tag;
        //教师
        $query_res = \app\admin\model\IdentityInfo::with(['user','clubDtl'])->where(['identity_type'=>'教师']);
        if(isset($params['tag'])&&$params['tag']){
            $query_res->whereRaw("FIND_IN_SET({$params['tag']}, tag) > 0");
        }
        if(isset($params['appointment_time'])&&$params['appointment_time']){
            switch ($params['appointment_time']){
                case '上午':
                    $query_res->whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) < '12:00:00' AND 
     TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) > '06:00:00')");
                    break;
                case '下午':
                    $query_res->whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) < '18:00:00' AND 
     TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) > '12:00:00')");
                    break;
                case '晚上':
                    $query_res->whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) < '24:00:00' AND 
     TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) > '18:00:00')");
                    break;
                default:
                    break;
            }
        }
        if(isset($params['area'])&&$params['area']){
            $query_res->whereRaw("FIND_IN_SET({$params['area']}, area) > 0");
        }
        if(isset($params['work_time'])&&$params['work_time']){
            switch ($params['work_time']){
                case 1:
                    $work_time_sql = "work_time < 1";
                    break;
                case 2:
                    $work_time_sql = "work_time >= 1 and work_time < 3";
                    break;
                case 3:
                    $work_time_sql = "work_time >= 3 and work_time < 5";
                    break;
                case 4:
                    $work_time_sql = "work_time >= 5 and work_time < 7";
                    break;
                case 5:
                    $work_time_sql = "work_time >= 7 and work_time < 10";
                    break;
                case 6:
                    $work_time_sql = "work_time >= 10 and work_time < 20";
                    break;
                case 7:
                    $work_time_sql = "work_time >= 20 and work_time < 30";
                    break;
                case 8:
                    $work_time_sql = "work_time >= 30";
                    break;
                default:
                    $work_time_sql = '';
                    break;
            }
            if($work_time_sql){
                $query_res->where($work_time_sql);
            }
        }
        if(isset($params['education_background'])&&$params['education_background']){
            $query_res->where("education_background = '{$params['education_background']}'");
        }
        if(isset($params['price'])&&$params['price']){
            switch ($params['price']){
                case 1:
                    $hourly_rate_sql = "hourly_rate < 200";
                    break;
                case 2:
                    $hourly_rate_sql = "hourly_rate >= 200 and hourly_rate < 300";
                    break;
                case 3:
                    $hourly_rate_sql = "hourly_rate >= 300 and hourly_rate < 400";
                    break;
                case 4:
                    $hourly_rate_sql = "hourly_rate >= 400 and hourly_rate < 500";
                    break;
                case 5:
                    $hourly_rate_sql = "hourly_rate >= 500 and hourly_rate < 700";
                    break;
                case 6:
                    $hourly_rate_sql = "hourly_rate >= 700 and hourly_rate < 1000";
                    break;
                case 7:
                    $hourly_rate_sql = "hourly_rate >= 1000 and hourly_rate < 2000";
                    break;
                case 8:
                    $hourly_rate_sql = "hourly_rate >= 2000";
                    break;
                default:
                    $hourly_rate_sql = '';
                    break;
            }
            if($hourly_rate_sql){
                $query_res->where($hourly_rate_sql);
            }
        }
        $query_res = $query_res->order('sort','desc')
            ->paginate($params['page_size']);

        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = $v['user_id'];
            $arr[$k]['name']     = $v['name'];
            $arr[$k]['club_dtl_name'] = $v['club_dtl']['name'];
            $arr[$k]['hourly_rate']    = $v['hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['score']);
            $arr[$k]['people']    = $v['people'];
            $arr[$k]['appointment_time_week']    = $v['appointment_time_week'].' '.$v['appointment_time'];
            $arr[$k]['avatar']    = $v['user']['avatar'];

            $area = $v['area'] ? explode(',',$v['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
        }
        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;
        $this->success('首页',$data);
    }

    public function home_pull(){
        $data = [];
//        $data['appointment_time'] = ['上午','下午','晚上'];//上课时间
        $data['gender'] = [
            [
                'id'=>1,
                'gender'=>'男',
            ],
            [
                'id'=>2,
                'gender'=>'女',
            ],
        ];

        $club = Club::field('id,sort,name')->with(['dtlf'])->order('sort','asc')->select();
        $data['club'] = $club;

        $area = TeacherArea::select();
        $data['area'] = $area;//上课区域
        $work_time = [
            [
                'id'=>1,
                'name'=>'1年内',
            ],
            [
                'id'=>2,
                'name'=>'1-3年内',
            ],
            [
                'id'=>3,
                'name'=>'3-5年内',
            ],
            [
                'id'=>4,
                'name'=>'5-7年内',
            ],
            [
                'id'=>5,
                'name'=>'7-10年内',
            ],
            [
                'id'=>6,
                'name'=>'10-20年内',
            ],
            [
                'id'=>7,
                'name'=>'20-30年内',
            ],
            [
                'id'=>8,
                'name'=>'30年及以上',
            ],
        ];
        //小学→初中→高中/中专→专科→本科→硕士→博士
        $education_background = ['小学','初中','高中','中专','大专','本科','硕士','博士'];
        $data['work_time'] = $work_time;
        $data['education_background'] = $education_background;

        $price = [
            [
                'id'=>1,
                'name'=>'200元内',
            ],
            [
                'id'=>2,
                'name'=>'200-300元内',
            ],
            [
                'id'=>3,
                'name'=>'300-400元内',
            ],
            [
                'id'=>4,
                'name'=>'400-500元内',
            ],
            [
                'id'=>5,
                'name'=>'500-700元内',
            ],
            [
                'id'=>6,
                'name'=>'700-1000元内',
            ],
            [
                'id'=>7,
                'name'=>'1000-2000元内',
            ],
            [
                'id'=>8,
                'name'=>'2000元及以上',
            ]
        ];
        $data['price'] = $price;
        $this->success('首页下拉',$data);
    }
    public function home_pull_old(){
        $data = [];
        $data['appointment_time'] = ['上午','下午','晚上'];//上课时间
        $area = TeacherArea::select();
        $data['area'] = $area;//上课区域
        $work_time = [
            [
                'id'=>1,
                'name'=>'1年内',
            ],
            [
                'id'=>2,
                'name'=>'1-3年内',
            ],
            [
                'id'=>3,
                'name'=>'3-5年内',
            ],
            [
                'id'=>4,
                'name'=>'5-7年内',
            ],
            [
                'id'=>5,
                'name'=>'7-10年内',
            ],
            [
                'id'=>6,
                'name'=>'10-20年内',
            ],
            [
                'id'=>7,
                'name'=>'20-30年内',
            ],
            [
                'id'=>8,
                'name'=>'30年及以上',
            ],
        ];
        //小学→初中→高中/中专→专科→本科→硕士→博士
        $education_background = ['小学','初中','高中','中专','大专','本科','硕士','博士'];
        $data['work_time'] = $work_time;
        $data['education_background'] = $education_background;

        $price = [
            [
                'id'=>1,
                'name'=>'200元内',
            ],
            [
                'id'=>2,
                'name'=>'200-300元内',
            ],
            [
                'id'=>3,
                'name'=>'300-400元内',
            ],
            [
                'id'=>4,
                'name'=>'400-500元内',
            ],
            [
                'id'=>5,
                'name'=>'500-700元内',
            ],
            [
                'id'=>6,
                'name'=>'700-1000元内',
            ],
            [
                'id'=>7,
                'name'=>'1000-2000元内',
            ],
            [
                'id'=>8,
                'name'=>'2000元及以上',
            ]
        ];
        $data['price'] = $price;
        $this->success('首页下拉',$data);
    }

    //精品课程
    public function get_premium(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }

        //教师
        $query_res = \app\admin\model\IdentityInfo::hasWhere('teacherDetailJp',function ($query)use($params){
            $query->where(['fa_teacher_detail.is_premium'=>1,'fa_teacher_detail.detail_status'=>1]);
            if(isset($params['club_one_id'])&&$params['club_one_id']){
                $query->where(['fa_teacher_detail.club_one_id'=>$params['club_one_id']]);
            }
            if(isset($params['club_two_id'])&&$params['club_two_id']){
                $query->where(['fa_teacher_detail.club_two_id'=>$params['club_two_id']]);
            }

            //工作经验
            if(isset($params['work_time'])&&$params['work_time']){
                switch ($params['work_time']){
                    case 1:
                        $work_time_sql = "work_time < 1";
                        break;
                    case 2:
                        $work_time_sql = "work_time >= 1 and work_time < 3";
                        break;
                    case 3:
                        $work_time_sql = "work_time >= 3 and work_time < 5";
                        break;
                    case 4:
                        $work_time_sql = "work_time >= 5 and work_time < 7";
                        break;
                    case 5:
                        $work_time_sql = "work_time >= 7 and work_time < 10";
                        break;
                    case 6:
                        $work_time_sql = "work_time >= 10 and work_time < 20";
                        break;
                    case 7:
                        $work_time_sql = "work_time >= 20 and work_time < 30";
                        break;
                    case 8:
                        $work_time_sql = "work_time >= 30";
                        break;
                    default:
                        $work_time_sql = '';
                        break;
                }
                if($work_time_sql){
                    $query->where($work_time_sql);
                }
            }
        });
        $query_res->with(['user','teacherDetailJp'=>function($query){
            // 只显示状态为1的课程
            $query->where(['detail_status'=>1]);
        }])->where(['identity_type'=>'教师','main_status'=>1]);

        if(isset($params['keyword'])&&$params['keyword']){
            $sql = "name like '%{$params['keyword']}%'";
            $club_dtl_keyword_id = ClubDtl::where("name like '%{$params['keyword']}%'")->column('id');
            if($club_dtl_keyword_id){
                $td_keyword_id = TeacherDetail::whereIn('club_two_id',$club_dtl_keyword_id)->column('info_id');
                if($td_keyword_id){
                    $user_id_keyword = \app\admin\model\IdentityInfo::whereIn('id',$td_keyword_id)->column('user_id');
                    if($user_id_keyword){
                        $user_id_keyword = implode(',',$user_id_keyword);
                        $sql = "(name like '%{$params['keyword']}%' or user_id in ({$user_id_keyword}))";
                    }
                }
            }
            $query_res->where($sql);
        }
        //地区
        if(isset($params['area'])&&$params['area']){
            $query_res->whereRaw("FIND_IN_SET({$params['area']}, area) > 0");
        }
        //标签
        if(isset($params['tag'])&&$params['tag']){
            $query_res->whereRaw("FIND_IN_SET({$params['tag']}, tag) > 0");
        }
        //可约时间
        if(isset($params['appointment_time'])&&$params['appointment_time']){
            $appointmentTime = trim($params['appointment_time']);
            $query_time = null;
            if (preg_match('/^\d{1,2}:\d{1,2}(?::\d{1,2})?$/', $appointmentTime)) {
                $parts = explode(':', $appointmentTime);
                $hour = str_pad($parts[0], 2, '0', STR_PAD_LEFT);
                $minute = str_pad($parts[1] ?? '00', 2, '0', STR_PAD_LEFT);
                $second = str_pad($parts[2] ?? '00', 2, '0', STR_PAD_LEFT);
                $query_time = "{$hour}:{$minute}:{$second}";
            } else {
                $timestamp = strtotime($appointmentTime);
                if ($timestamp !== false) {
                    $query_time = date('H:i:s', $timestamp);
                }
            }
            if ($query_time) {
                $query_res->whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) <= '{$query_time}' AND 
    TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) >= '{$query_time}')");
            }
        }
        //最高学历
        if(isset($params['education_background'])&&$params['education_background']){
            $query_res->where('fa_identity_info.education_background',$params['education_background']);
        }
        //金额
        if(isset($params['price'])&&$params['price']){
            switch ($params['price']){
                case 1:
                    $hourly_rate_sql = "lowest_hourly_rate < 200";
                    break;
                case 2:
                    $hourly_rate_sql = "lowest_hourly_rate >= 200 and lowest_hourly_rate < 300";
                    break;
                case 3:
                    $hourly_rate_sql = "lowest_hourly_rate >= 300 and lowest_hourly_rate < 400";
                    break;
                case 4:
                    $hourly_rate_sql = "lowest_hourly_rate >= 400 and lowest_hourly_rate < 500";
                    break;
                case 5:
                    $hourly_rate_sql = "lowest_hourly_rate >= 500 and lowest_hourly_rate < 700";
                    break;
                case 6:
                    $hourly_rate_sql = "lowest_hourly_rate >= 700 and lowest_hourly_rate < 1000";
                    break;
                case 7:
                    $hourly_rate_sql = "lowest_hourly_rate >= 1000 and lowest_hourly_rate < 2000";
                    break;
                case 8:
                    $hourly_rate_sql = "lowest_hourly_rate >= 2000";
                    break;
                default:
                    $hourly_rate_sql = '';
                    break;
            }
            if($hourly_rate_sql){
                $query_res->where($hourly_rate_sql);
            }
        }
        //性别
        if(isset($params['gender'])&&$params['gender']){
            if($params['gender'] == 1){
                $gender_user_id_arr = \app\admin\model\User::where(['gender'=>1])->column('id');
                $query_res->whereIn('user_id',$gender_user_id_arr);
            }
            if($params['gender'] == 2){
                $gender_user_id_arr = \app\admin\model\User::where(['gender'=>0])->column('id');
                $query_res->whereIn('user_id',$gender_user_id_arr);
            }
        }
        $query_res->where("lowest_hourly_rate > 0");
        if(isset($params['area_sort'])&&$params['area_sort']){
            //当前地址地区排序 - 包含传入值的排在最前面，其他按order_num排序
            $area_sort = (int)$params['area_sort']; // 转换为整数防止SQL注入
            $query_res = $query_res->orderRaw("FIND_IN_SET({$area_sort}, area)>0 DESC");
        }

        if(isset($params['sort_type'])&&$params['sort_type']){
            if($params['sort_type']!='desc'&&$params['sort_type']!='asc'&&$params['sort_type']!='DESC'&&$params['sort_type']!='ASC'){
                $this->error('排序方式参数错误');
            }
        }
        if(isset($params['sort_name'])&&$params['sort_name']){
            switch ($params['sort_name']){
                case "score":
                    if(isset($params['sort_type'])&&$params['sort_type']){
                        $query_res = $query_res->order('main_score',$params['sort_type']);
                    }else{
                        $query_res = $query_res->order('main_score','desc');
                    }
                    break;
                case "price":
                    if(isset($params['sort_type'])&&$params['sort_type']) {
                        $query_res = $query_res->order('lowest_hourly_rate',$params['sort_type']);
                    }else{
                        $query_res = $query_res->order('lowest_hourly_rate', 'desc');
                    }
                    break;
                default:
                    break;
            }
        }

        $query_res = $query_res->order('main_people','desc');
        $query_res = $query_res->paginate($params['page_size']);

        $list = $query_res->getCollection();
        
        // 获取当前登录用户（如果已登录）
        $current_user_id = null;
        try {
            $current_user = $this->auth->getUser();
            if (isset($current_user['id']) && $current_user['id']) {
                $current_user_id = $current_user['id'];
            }
        } catch (\Exception $e) {
            // 用户未登录，忽略
        }

        // 如果用户已登录，批量查询收藏状态
        $collected_teacher_detail_ids = [];
        if ($current_user_id) {
            // 收集所有teacher_detail_id
            $all_teacher_detail_ids = [];
            foreach ($list as $v) {
                foreach ($v['teacher_detail_jp'] as $vv) {
                    if (isset($vv['id'])) {
                        $all_teacher_detail_ids[] = $vv['id'];
                    }
                }
            }
            // 批量查询收藏状态
            if (!empty($all_teacher_detail_ids)) {
                $collected_teacher_detail_ids = TeacherCollection::where(['user_id' => $current_user_id])
                    ->whereIn('teacher_detail_id', array_unique($all_teacher_detail_ids))
                    ->column('teacher_detail_id');
            }
        }

        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = $v['user_id'];
            $arr[$k]['name']     = $v['name'];
            $club_dtl_name = [];
            $teacher_detail = [];
            foreach ($v['teacher_detail_jp'] as $kk=>$vv){
                if(isset($vv['club_dtl_s']['name'])&&$vv['club_dtl_s']['name']){
                    $club_dtl_name[] = $vv['club_dtl_s']['name'];
                }
                $teacher_detail[$kk]['id'] = $vv['id'];
                $teacher_detail[$kk]['info_id'] = $vv['info_id'];
                $teacher_detail[$kk]['hourly_rate'] = $vv['hourly_rate'];
                $teacher_detail[$kk]['club_name'] = isset($vv['club_dtl_s']['name']) ? $vv['club_dtl_s']['name'] : '';
                $teacher_detail[$kk]['club_img_url'] = isset($vv['club_dtl_s']['img_url']) ? $vv['club_dtl_s']['img_url'] : '';
                $teacher_detail[$kk]['is_premium'] = $vv['is_premium'];
                $teacher_detail[$kk]['people'] = $vv['people'];
                if($vv['work_time']>0){
                    $teacher_detail[$kk]['work_time'] = $vv['work_time'].'年';
                }else{
                    $teacher_detail[$kk]['work_time'] = '';
                }
                // 检查该课程是否被收藏
                $is_collected = 2; // 默认2=未收藏
                if ($current_user_id && isset($vv['id']) && in_array($vv['id'], $collected_teacher_detail_ids)) {
                    $is_collected = 1; // 1=已收藏
                }
                $teacher_detail[$kk]['is_collected'] = $is_collected; // 1已收藏，2未收藏
            }
            $club_dtl_name = array_values(array_unique($club_dtl_name));
            $arr[$k]['club_dtl_name'] = $club_dtl_name;
            $arr[$k]['hourly_rate']    = $v['lowest_hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['main_score']);
            $arr[$k]['people']    = $v['main_people'];
            $arr[$k]['order_num']    = $v['order_num_all'];
            $arr[$k]['education_background']    = $v['education_background'];
            $week = isset($v['appointment_time_week']) ? $v['appointment_time_week'] : '';
            $time = isset($v['appointment_time']) ? $v['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $arr[$k]['avatar']    = $v['user']['avatar'];

            $area = $v['area'] ? explode(',',$v['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
            $arr[$k]['dtl']    = $teacher_detail;
        }

        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;

        $this->success('精品课程列表',$data);
        exit;


        $query_res = \app\admin\model\TeacherDetail::with(['identity','club_dtl'])->where(['is_premium'=>1]);
        $query_res = $query_res->order('sort','desc')
            ->paginate($params['page_size']);

        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = isset($v['identity']['user_id']) ? $v['identity']['user_id'] : '';
            $arr[$k]['name']     = isset($v['identity']['name']) ? $v['identity']['name'] : '';
            $arr[$k]['club_dtl_name'] = isset($v['club_dtl']['name']) ? $v['club_dtl']['name'] : '';
            $arr[$k]['hourly_rate']    = $v['hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['score']);
            $arr[$k]['people']    = $v['people'];
            $arr[$k]['order_num']    = $v['order_num'];
            $arr[$k]['is_premium']    = $v['is_premium'];
            $week = isset($v['identity']['appointment_time_week']) ? $v['identity']['appointment_time_week'] : '';
            $time = isset($v['identity']['appointment_time']) ? $v['identity']['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $arr[$k]['avatar']    = $v['identity']['user']['avatar'];

            $area = $v['identity']['area'] ? explode(',',$v['identity']['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
        }
        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;
        $this->success('首页',$data);
    }
    public function get_premium_old(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }

        $query_res = \app\admin\model\IdentityInfo::with(['user','clubDtl'])->where(['identity_info.is_premium'=>1]);
        $query_res = $query_res->order('sort','desc')
            ->paginate($params['page_size']);

        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = $v['user_id'];
            $arr[$k]['name']     = $v['name'];
            $arr[$k]['club_dtl_name'] = $v['club_dtl']['name'];
            $arr[$k]['hourly_rate']    = $v['hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['score']);
            $arr[$k]['people']    = $v['people'];
            $arr[$k]['appointment_time_week']    = $v['appointment_time_week'].' '.$v['appointment_time'];
            $arr[$k]['avatar']    = $v['user']['avatar'];

            $area = $v['area'] ? explode(',',$v['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
        }
        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;
        $this->success('首页',$data);
    }

    //检查课程进度
    public function class_jd(){
        $time = date('H:i:s');
        $date = date('Y-m-d');
        $md = date('m-d');
        $week = date('N');
        $week_name = '周'.TeacherClassDtl::numberToChinese($week);

//        $class = Db::query("SELECT
//	a.*,
//	ADDTIME(
//		a.time_start,
//	SEC_TO_TIME( a.class_num * 40 * 60 )) AS end_time
//FROM
//	fa_teacher_class_dtl a LEFT JOIN fa_teacher_class b on  a.teacher_class_id = b.id
//WHERE
//	a.`status` = 1 and b.`status` = 1 and a.is_send_notice = 1 and b.start_date > '{$date}'
//	AND ( a.week_date = '{$date}' OR a.week_date = '{$week_name}' )
//HAVING
//	end_time < '{$time}'");

        $defaultDuration = Config::get('course.default_course_duration', '');
        $duration = $defaultDuration;
        $class = Db::query("SELECT
	a.*,
	ADDTIME(
		a.time_start,
	SEC_TO_TIME( a.class_num * (
                CASE
                    WHEN c.course_duration IS NULL OR c.course_duration <= 0 THEN {$duration}
                    ELSE c.course_duration
                END
            ) * 60 )) AS end_time
FROM
	fa_teacher_class_dtl a LEFT JOIN fa_teacher_class b on  a.teacher_class_id = b.id
	left join fa_teacher_detail c on b.teacher_detail_id = c.id
WHERE
	a.`status` = 1 and b.`status` = 1 and a.is_send_notice = 1 and b.start_date <= '{$date}'
	AND ( a.week_date = '{$date}' OR a.week_date = '{$week_name}' ) AND ADDTIME(a.time_start, SEC_TO_TIME(a.class_num * (
                CASE
                    WHEN c.course_duration IS NULL OR c.course_duration <= 0 THEN {$duration}
                    ELSE c.course_duration
                END
            ) * 60)) < '{$time}'");

        $send_add_notice = [];
        $ids = [];
        foreach ($class as $k=>$v){
            $teacher = TeacherClass::where(['id'=>$v['teacher_class_id']])->with(['teachers'])->find();
            $td = TeacherDetail::where(['id'=>$teacher['teacher_detail_id']])->find();
            $club_dtl_name = '';
            if($td){
                $club_dtl = ClubDtl::where(['id'=>$td['club_two_id']])->find();
                $club_dtl_name = isset($club_dtl['name']) ? $club_dtl['name'] : '';
            }
            $teacher_name = '';
            if($teacher){
                $teacher_name = isset($teacher['teachers']['nickname']) ? $teacher['teachers']['nickname'] : '';
            }
            $title_content = $teacher_name;
            if($club_dtl_name){
                $title_content .= "({$club_dtl_name})";
            }
            $title_content .= '当日课程确认';
            $send_add_notice[$k]['title'] = $title_content;//标题
            $content = "{$teacher_name}.是否完成{$md}的授课计划,请选择是或否,24小时未确认系统将自动确认该课程完成";
            $send_add_notice[$k]['content'] = $content;//内容
            $send_add_notice[$k]['need_confirm'] = 1;//是否需要确认 1是 2否
            $send_add_notice[$k]['jump'] = '课程详情';//跳转地址
            $send_add_notice[$k]['teacher_class_id'] = $v['teacher_class_id'];//课程id
            $send_add_notice[$k]['teacher_class_dtl_id'] = $v['id'];//课程安排id
            $send_add_notice[$k]['send_user_id'] = $teacher['teacher_id'];//发送人id
            $send_add_notice[$k]['get_user_id'] = $teacher['user_id'];//接收人id
            $send_add_notice[$k]['identity_type'] = '校方';//接收人身份
            $send_add_notice[$k]['addtime'] = date('Y-m-d H:i:s');//添加时间
            $send_add_notice[$k]['is_read'] = 1;//是否已读 1未读 2已读
            $send_add_notice[$k]['class_num'] = $v['class_num'];//课时
            $ids[] = $v['id'];
        }
        //给校方发通知 课程确认
        if(count($send_add_notice)){
            Notice::insertAll($send_add_notice);
            // 发送个推消息
            foreach ($send_add_notice as $notice) {
                Notice::sendGetuiPush($notice);
            }
        }
        if(count($ids)){
            TeacherClassDtl::whereIn('id',$ids)->update(['is_send_notice'=>2]);
        }

        $datetime = date('Y-m-d H:i:s', strtotime('-1 day'));
        $notice = Notice::where("jump in ('课程详情','课程详情补课') and need_confirm = 1 and confirm_status = 1 and addtime < '{$datetime}'")->select();
        $notice_ids = [];
        foreach ($notice as $k=>$v){
            //自动确认 增加进度
            $send_date = date('Y-m-d',strtotime($v['addtime']));
            $date = date('Y-m-d');
            $week = date('N');
            if($send_date!=$date&&$week==1){
                TeacherClassDtl::jd($v['teacher_class_dtl_id'],$v['teacher_class_id'],$v['class_num'],1);
            }else{
                TeacherClassDtl::jd($v['teacher_class_dtl_id'],$v['teacher_class_id'],$v['class_num']);
            }
            if($v['jump'] == '课程详情补课'){
                if($v['sf_id']){
                    AskForLeave::where(['id'=>$v['sf_id']])->update(['is_wc'=>1]);
                }
            }
            $notice_ids[] = $v['id'];
        }
        if(count($notice_ids)){
            Notice::whereIn('id',$notice_ids)->update(['confirm_status'=>2]);
        }
        AskForLeave::where(['is_send'=>0,'status'=>2,'make_up_classes_time'=>date('Y-m-d 00:00:00')])->select();
        $make_up_time = date('Y-m-d 00:00:00');

        $class_bk = Db::query("SELECT
	a.*,
	ADDTIME(
		a.bk_time,
	SEC_TO_TIME( a.bk_class_num * (
                CASE
                    WHEN c.course_duration IS NULL OR c.course_duration <= 0 THEN {$duration}
                    ELSE c.course_duration
                END
            ) * 60 )) AS end_time
FROM
	fa_ask_for_leave a
	left join fa_teacher_class b on a.class_id = b.id
	left join fa_teacher_detail c on b.teacher_detail_id = c.id
WHERE
	a.`status` = 2 and a.`is_send` = 0 and a.`make_up_classes_time` = '{$make_up_time}'
	 AND ADDTIME(a.bk_time, SEC_TO_TIME(a.bk_class_num * (
                CASE
                    WHEN c.course_duration IS NULL OR c.course_duration <= 0 THEN {$duration}
                    ELSE c.course_duration
                END
            ) * 60)) < '{$time}'");
//HAVING
//	end_time < '{$time}'");

        $send_add_notice = [];
        $ids = [];
        foreach ($class_bk as $k=>$v){
            $teacher = TeacherClass::where(['id'=>$v['class_id']])->with(['teachers'])->find();
            $teacher_name = '';
            if($teacher){
                $teacher_name = isset($teacher['teachers']['nickname']) ? $teacher['teachers']['nickname'] : '';
            }
            $send_add_notice[$k]['title'] = $teacher_name.'当日补课确认';//标题
            $content = "{$teacher_name}.是否完成{$md}的补课计划,请选择是或否,24小时未确认系统将自动确认该课程完成";
            $send_add_notice[$k]['content'] = $content;//内容
            $send_add_notice[$k]['need_confirm'] = 1;//是否需要确认 1是 2否
            $send_add_notice[$k]['jump'] = '课程详情补课';//跳转地址
            $send_add_notice[$k]['teacher_class_id'] = $v['class_id'];//课程id
            $send_add_notice[$k]['teacher_class_dtl_id'] = 0;//课程安排id
            $send_add_notice[$k]['send_user_id'] = $teacher['teacher_id'];//发送人id
            $send_add_notice[$k]['get_user_id'] = $teacher['user_id'];//接收人id
            $send_add_notice[$k]['identity_type'] = '校方';//接收人身份
            $send_add_notice[$k]['addtime'] = date('Y-m-d H:i:s');//添加时间
            $send_add_notice[$k]['is_read'] = 1;//是否已读 1未读 2已读
            $send_add_notice[$k]['class_num'] = $v['class_num'];//课时
            $ids[] = $v['id'];
        }
        //给校方发通知 课程确认
        if(count($send_add_notice)){
            Notice::insertAll($send_add_notice);
            // 发送个推消息
            foreach ($send_add_notice as $notice) {
                Notice::sendGetuiPush($notice);
            }
        }
        if(count($ids)){
            AskForLeave::whereIn('id',$ids)->update(['is_send'=>1]);
        }
        return 'success';
    }
    public function class_jd_old(){
        $time = date('H:i:s');
        $date = date('Y-m-d');
        $md = date('m-d');
        $week = date('N');
        $week_name = '周'.TeacherClassDtl::numberToChinese($week);

//        $class = Db::query("SELECT
//	a.*,
//	ADDTIME(
//		a.time_start,
//	SEC_TO_TIME( a.class_num * 40 * 60 )) AS end_time
//FROM
//	fa_teacher_class_dtl a LEFT JOIN fa_teacher_class b on  a.teacher_class_id = b.id
//WHERE
//	a.`status` = 1 and b.`status` = 1 and a.is_send_notice = 1 and b.start_date > '{$date}'
//	AND ( a.week_date = '{$date}' OR a.week_date = '{$week_name}' )
//HAVING
//	end_time < '{$time}'");

        $class = Db::query("SELECT
	a.*,
	ADDTIME(
		a.time_start,
	SEC_TO_TIME( a.class_num * 40 * 60 )) AS end_time
FROM
	fa_teacher_class_dtl a LEFT JOIN fa_teacher_class b on  a.teacher_class_id = b.id
WHERE
	a.`status` = 1 and b.`status` = 1 and a.is_send_notice = 1 and b.start_date > '{$date}'
	AND ( a.week_date = '{$date}' OR a.week_date = '{$week_name}' ) AND ADDTIME(a.time_start, SEC_TO_TIME(a.class_num * 40 * 60)) < '{$time}'");

        $send_add_notice = [];
        $ids = [];
        foreach ($class as $k=>$v){
            $teacher = TeacherClass::where(['id'=>$v['teacher_class_id']])->with(['teachers'])->find();
            $teacher_name = '';
            if($teacher){
                $teacher_name = isset($teacher['teachers']['nickname']) ? $teacher['teachers']['nickname'] : '';
            }
            $send_add_notice[$k]['title'] = $teacher_name.'当日课程确认';//标题
            $content = "{$teacher_name}.是否完成{$md}的授课计划,请选择是或否,24小时未确认系统将自动确认该课程完成";
            $send_add_notice[$k]['content'] = $content;//内容
            $send_add_notice[$k]['need_confirm'] = 1;//是否需要确认 1是 2否
            $send_add_notice[$k]['jump'] = '课程详情';//跳转地址
            $send_add_notice[$k]['teacher_class_id'] = $v['teacher_class_id'];//课程id
            $send_add_notice[$k]['teacher_class_dtl_id'] = $v['id'];//课程安排id
            $send_add_notice[$k]['send_user_id'] = $teacher['teacher_id'];//发送人id
            $send_add_notice[$k]['get_user_id'] = $teacher['user_id'];//接收人id
            $send_add_notice[$k]['identity_type'] = '校方';//接收人身份
            $send_add_notice[$k]['addtime'] = date('Y-m-d H:i:s');//添加时间
            $send_add_notice[$k]['is_read'] = 1;//是否已读 1未读 2已读
            $send_add_notice[$k]['class_num'] = $v['class_num'];//课时
            $ids[] = $v['id'];
        }
        //给校方发通知 课程确认
        if(count($send_add_notice)){
            Notice::insertAll($send_add_notice);
            // 发送个推消息
            foreach ($send_add_notice as $notice) {
                Notice::sendGetuiPush($notice);
            }
        }
        if(count($ids)){
            TeacherClassDtl::whereIn('id',$ids)->update(['is_send_notice'=>2]);
        }

        $datetime = date('Y-m-d H:i:s', strtotime('-1 day'));
        $notice = Notice::where("jump in ('课程详情','课程详情补课') and need_confirm = 1 and confirm_status = 1 and addtime < '{$datetime}'")->select();
        $notice_ids = [];
        foreach ($notice as $k=>$v){
            //自动确认 增加进度
            $send_date = date('Y-m-d',strtotime($v['addtime']));
            $date = date('Y-m-d');
            $week = date('N');
            if($send_date!=$date&&$week==1){
                TeacherClassDtl::jd($v['teacher_class_dtl_id'],$v['teacher_class_id'],$v['class_num'],1);
            }else{
                TeacherClassDtl::jd($v['teacher_class_dtl_id'],$v['teacher_class_id'],$v['class_num']);
            }
            if($v['jump'] == '课程详情补课'){
                if($v['sf_id']){
                    AskForLeave::where(['id'=>$v['sf_id']])->update(['is_wc'=>1]);
                }
            }
            $notice_ids[] = $v['id'];
        }
        if(count($notice_ids)){
            Notice::whereIn('id',$notice_ids)->update(['confirm_status'=>2]);
        }
        AskForLeave::where(['is_send'=>0,'status'=>2,'make_up_classes_time'=>date('Y-m-d 00:00:00')])->select();
        $make_up_time = date('Y-m-d 00:00:00');

        $class_bk = Db::query("SELECT
	a.*,
	ADDTIME(
		a.bk_time,
	SEC_TO_TIME( a.bk_class_num * 40 * 60 )) AS end_time
FROM
	fa_ask_for_leave a
WHERE
	a.`status` = 2 and a.`is_send` = 0 and a.`make_up_classes_time` = '{$make_up_time}'
	 AND ADDTIME(a.bk_time, SEC_TO_TIME(a.bk_class_num * 40 * 60)) < '{$time}'");
//HAVING
//	end_time < '{$time}'");

        $send_add_notice = [];
        $ids = [];
        foreach ($class_bk as $k=>$v){
            $teacher = TeacherClass::where(['id'=>$v['class_id']])->with(['teachers'])->find();
            $teacher_name = '';
            if($teacher){
                $teacher_name = isset($teacher['teachers']['nickname']) ? $teacher['teachers']['nickname'] : '';
            }
            $send_add_notice[$k]['title'] = $teacher_name.'当日补课确认';//标题
            $content = "{$teacher_name}.是否完成{$md}的补课计划,请选择是或否,24小时未确认系统将自动确认该课程完成";
            $send_add_notice[$k]['content'] = $content;//内容
            $send_add_notice[$k]['need_confirm'] = 1;//是否需要确认 1是 2否
            $send_add_notice[$k]['jump'] = '课程详情补课';//跳转地址
            $send_add_notice[$k]['teacher_class_id'] = $v['class_id'];//课程id
            $send_add_notice[$k]['teacher_class_dtl_id'] = 0;//课程安排id
            $send_add_notice[$k]['send_user_id'] = $teacher['teacher_id'];//发送人id
            $send_add_notice[$k]['get_user_id'] = $teacher['user_id'];//接收人id
            $send_add_notice[$k]['identity_type'] = '校方';//接收人身份
            $send_add_notice[$k]['addtime'] = date('Y-m-d H:i:s');//添加时间
            $send_add_notice[$k]['is_read'] = 1;//是否已读 1未读 2已读
            $send_add_notice[$k]['class_num'] = $v['class_num'];//课时
            $ids[] = $v['id'];
        }
        //给校方发通知 课程确认
        if(count($send_add_notice)){
            Notice::insertAll($send_add_notice);
            // 发送个推消息
            foreach ($send_add_notice as $notice) {
                Notice::sendGetuiPush($notice);
            }
        }
        if(count($ids)){
            AskForLeave::whereIn('id',$ids)->update(['is_send'=>1]);
        }
        return 'success';
    }

    //周末修改状态
    public function weekend_up(){
        $week = date('N');
        $date = date('H:i:s');
        $date_s = date('Y-m-d');
        //确认是周末才可以改
        if($week == 7&&$date>'23:00:00'){
            $class_id = TeacherClass::where(['status'=>1,'period_set'=>1])->where("start_date <= {$date_s}")->column('id');
            $dtl = TeacherClassDtl::whereIn('teacher_class_id',$class_id)->whereLike('week_date','周')->where(['is_xs'=>1])->select();

            TeacherClassDtl::whereIn('teacher_class_id',$class_id)->whereLike('week_date','周')->update(['is_xs'=>2]);
            foreach ($dtl as $k=>$v){
                $add = [];
                $add['teacher_class_id'] = $v['teacher_class_id'];//课程id
                $add['week_date'] = $v['week_date'];//日/周
                $add['time_start'] = $v['time_start'];//开始时间
                $add['class_num'] = $v['class_num'];//课时
                $add['cycle'] = $v['cycle'];//周期 1每周 2日期
                $add['status'] = 1;//状态 1未开始 2已完成 3已请假
                $add['is_send_notice'] = 1;//是否发送消息 1否 2是
                $add['is_send_sj_notice'] = 1;//是否发送即将上课消息 1否 2是

                //这里的$v['week_date'] 是本周的周几 然后 下面的date我要存对应下周的日期，比如 week_date是周一(也就是2025-11-17) 那么 下面的date就是 2025-11-24
                // 如果已有date字段（本周的日期），直接加7天得到下周的日期
                $add['date'] = $this->getWeekdayDate($v['week_date']);
                $add['is_xs'] = 1;//是否显示在详情(用于日历展示) 1展示 2不展示
                TeacherClassDtl::insertAll($add);
            }
//            TeacherClassDtl::whereIn('teacher_class_id',$class_id)->whereLike('week_date','周')->update(['status'=>1,'is_send_notice'=>1]);
        }
        return 'success';
    }

    function getWeekdayDate($weekday) {
        // 设置时区确保日期计算准确
        date_default_timezone_set('Asia/Shanghai');

        // 定义星期映射关系
        $weekday_map = [
            '周一' => 1, '星期一' => 1,'星期二' => 2, '周二' => 2, '星期三' => 3, '周三' => 3,
            '星期四' => 4, '周四' => 4, '星期五' => 5, '周五' => 5,
            '星期六' => 6, '周六' => 6, '星期日' => 7, '周日' => 7,'周天' => 7, '星期天' => 7
        ];

        // 检查传入的星期参数是否有效
        if (!isset($weekday_map[$weekday])) {
            return "错误：无效的星期参数，请使用如'周一'、'周二'等格式";
        }

        $current_weekday = date('w'); // 获取当前星期几，0为周日，1-6为周一到周六
        $target_weekday = $weekday_map[$weekday];

        // 修复逻辑：计算本周目标日期
        $day_diff = $target_weekday - $current_weekday;

        // 如果目标星期在当前星期之前，需要加上7天来获取本周日期
//        if ($day_diff < 0) {
        $day_diff += 7;
//        }
        // 使用strtotime计算目标日期
        $target_date = date('Y-m-d', strtotime("+{$day_diff} days"));

        return $target_date;
    }
    //首页搜索结果
    public function get_key_club(){
        $params = $this->request->param();
        if(!isset($params['keyword'])||!$params['keyword']){
            $this->error('缺少查询条件');
        }
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        if(!isset($params['club_page'])||!$params['club_page']){
            $params['club_page'] = 1;
        }
        if(!isset($params['club_page_size'])||!$params['club_page_size']){
            $params['club_page_size'] = 10;
        }
        $query_res = ClubDtl::where("name like '%{$params['keyword']}%'")->with(['clubs']);
        $query_res = $query_res->order('club_id','asc')->order('sort','desc')
            ->paginate($params['club_page_size'], false, ['var_page' => 'club_page']);

        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['club_id'] = $v['club_id'];
            $arr[$k]['club_name'] = isset($v['clubs']) ? $v['clubs']['club_name'] : '';
            $arr[$k]['club_img'] = isset($v['clubs']) ? isset($v['clubs']['club_img']) ? $v['clubs']['club_img'] : '' : '';
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['name'] = $v['name'] ? $v['name'] : '';
            $arr[$k]['img'] = $v['img_url'] ? $v['img_url'] : '';
        }
        $count = $query_res->total();

        $data = [];
        $data['list'] = $arr;
        $data['count'] = $count;

        $club_dtl_id = ClubDtl::where("name like '%{$params['keyword']}%'")->column('id');
        $club_id = Club::where("name like '%{$params['keyword']}%'")->column('id');

        $club_id_str = implode(',',$club_id);
        $club_dtl_id_str = implode(',',$club_dtl_id);
        
        // 先查询匹配name的identity_info的id
        $identity_ids = \app\admin\model\IdentityInfo::where('name', 'like', "%{$params['keyword']}%")->column('id');
        $identity_ids_str = !empty($identity_ids) ? implode(',', $identity_ids) : '0';

        //教师
        $query_res = \app\admin\model\IdentityInfo::hasWhere('teacherDetail',function ($query)use($params){
            if(isset($params['club_one_id'])&&$params['club_one_id']){
                $query->where(['fa_teacher_detail.club_one_id'=>$params['club_one_id']]);
            }
            if(isset($params['club_two_id'])&&$params['club_two_id']){
                $query->where(['fa_teacher_detail.club_two_id'=>$params['club_two_id']]);
            }

            //工作经验
            if(isset($params['work_time'])&&$params['work_time']){
                switch ($params['work_time']){
                    case 1:
                        $work_time_sql = "work_time < 1";
                        break;
                    case 2:
                        $work_time_sql = "work_time >= 1 and work_time < 3";
                        break;
                    case 3:
                        $work_time_sql = "work_time >= 3 and work_time < 5";
                        break;
                    case 4:
                        $work_time_sql = "work_time >= 5 and work_time < 7";
                        break;
                    case 5:
                        $work_time_sql = "work_time >= 7 and work_time < 10";
                        break;
                    case 6:
                        $work_time_sql = "work_time >= 10 and work_time < 20";
                        break;
                    case 7:
                        $work_time_sql = "work_time >= 20 and work_time < 30";
                        break;
                    case 8:
                        $work_time_sql = "work_time >= 30";
                        break;
                    default:
                        $work_time_sql = '';
                        break;
                }
                if($work_time_sql){
                    $query->where($work_time_sql);
                }
            }
        });
        $query_res->with(['user','teacherDetail'=>function($query){
            // 只显示状态为1的课程
            $query->where(['detail_status'=>1]);
        }])->where(['identity_type'=>'教师','main_status'=>1]);

        if(isset($params['keyword'])&&$params['keyword']){
            $sql = "name like '%{$params['keyword']}%'";
            $club_dtl_keyword_id = ClubDtl::where("name like '%{$params['keyword']}%'")->column('id');
            if($club_dtl_keyword_id){
                $td_keyword_id = TeacherDetail::whereIn('club_two_id',$club_dtl_keyword_id)->column('info_id');
                if($td_keyword_id){
                    $user_id_keyword = \app\admin\model\IdentityInfo::whereIn('id',$td_keyword_id)->column('user_id');
                    if($user_id_keyword){
                        $user_id_keyword = implode(',',$user_id_keyword);
                        $sql = "(name like '%{$params['keyword']}%' or user_id in ({$user_id_keyword}))";
                    }
                }
            }
            $query_res->where($sql);
        }
        //社团课程筛选
//        if(isset($params['club_one_id'])&&$params['club_one_id']){
//            $query_res->hasWhere('teacherDetail',['club_one_id'=>$params['club_one_id']]);
//        }
//        if(isset($params['club_two_id'])&&$params['club_two_id']){
//            $query_res->hasWhere('teacherDetail',['club_two_id'=>$params['club_two_id']]);
//        }
        //地区
        if(isset($params['area'])&&$params['area']){
            $query_res->whereRaw("FIND_IN_SET({$params['area']}, area) > 0");
        }
        //标签
        if(isset($params['tag'])&&$params['tag']){
            $query_res->whereRaw("FIND_IN_SET({$params['tag']}, tag) > 0");
        }
        //可约时间
        if(isset($params['appointment_time'])&&$params['appointment_time']){
            $appointmentTime = trim($params['appointment_time']);
            $query_time = null;
            if (preg_match('/^\d{1,2}:\d{1,2}(?::\d{1,2})?$/', $appointmentTime)) {
                $parts = explode(':', $appointmentTime);
                $hour = str_pad($parts[0], 2, '0', STR_PAD_LEFT);
                $minute = str_pad($parts[1] ?? '00', 2, '0', STR_PAD_LEFT);
                $second = str_pad($parts[2] ?? '00', 2, '0', STR_PAD_LEFT);
                $query_time = "{$hour}:{$minute}:{$second}";
            } else {
                $timestamp = strtotime($appointmentTime);
                if ($timestamp !== false) {
                    $query_time = date('H:i:s', $timestamp);
                }
            }
            if ($query_time) {
                $query_res->whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) <= '{$query_time}' AND 
    TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) >= '{$query_time}')");
            }
        }
        //最高学历
        if(isset($params['education_background'])&&$params['education_background']){
            $query_res->where('fa_identity_info.education_background',$params['education_background']);
        }
        //金额
        if(isset($params['price'])&&$params['price']){
            switch ($params['price']){
                case 1:
                    $hourly_rate_sql = "lowest_hourly_rate < 200";
                    break;
                case 2:
                    $hourly_rate_sql = "lowest_hourly_rate >= 200 and lowest_hourly_rate < 300";
                    break;
                case 3:
                    $hourly_rate_sql = "lowest_hourly_rate >= 300 and lowest_hourly_rate < 400";
                    break;
                case 4:
                    $hourly_rate_sql = "lowest_hourly_rate >= 400 and lowest_hourly_rate < 500";
                    break;
                case 5:
                    $hourly_rate_sql = "lowest_hourly_rate >= 500 and lowest_hourly_rate < 700";
                    break;
                case 6:
                    $hourly_rate_sql = "lowest_hourly_rate >= 700 and lowest_hourly_rate < 1000";
                    break;
                case 7:
                    $hourly_rate_sql = "lowest_hourly_rate >= 1000 and lowest_hourly_rate < 2000";
                    break;
                case 8:
                    $hourly_rate_sql = "lowest_hourly_rate >= 2000";
                    break;
                default:
                    $hourly_rate_sql = '';
                    break;
            }
            if($hourly_rate_sql){
                $query_res->where($hourly_rate_sql);
            }
        }
        //性别
        if(isset($params['gender'])&&$params['gender']){
            if($params['gender'] == 1){
                $gender_user_id_arr = \app\admin\model\User::where(['gender'=>1])->column('id');
                $query_res->whereIn('user_id',$gender_user_id_arr);
            }
            if($params['gender'] == 2){
                $gender_user_id_arr = \app\admin\model\User::where(['gender'=>0])->column('id');
                $query_res->whereIn('user_id',$gender_user_id_arr);
            }
        }
        $query_res->where("lowest_hourly_rate > 0");
        if(isset($params['area_sort'])&&$params['area_sort']){
            //当前地址地区排序 - 包含传入值的排在最前面，其他按order_num排序
            $area_sort = (int)$params['area_sort']; // 转换为整数防止SQL注入
            $query_res = $query_res->orderRaw("FIND_IN_SET({$area_sort}, area)>0 DESC");
        }

        if(isset($params['sort_type'])&&$params['sort_type']){
            if($params['sort_type']!='desc'&&$params['sort_type']!='asc'&&$params['sort_type']!='DESC'&&$params['sort_type']!='ASC'){
                $this->error('排序方式参数错误');
            }
        }
        if(isset($params['sort_name'])&&$params['sort_name']){
            switch ($params['sort_name']){
                case "score":
                    if(isset($params['sort_type'])&&$params['sort_type']){
                        $query_res = $query_res->order('main_score',$params['sort_type']);
                    }else{
                        $query_res = $query_res->order('main_score','desc');
                    }
                    break;
                case "price":
                    if(isset($params['sort_type'])&&$params['sort_type']) {
                        $query_res = $query_res->order('lowest_hourly_rate',$params['sort_type']);
                    }else{
                        $query_res = $query_res->order('lowest_hourly_rate', 'desc');
                    }
                    break;
                default:
                    break;
            }
        }

        $query_res = $query_res->order('main_people','desc');
        $query_res = $query_res->paginate($params['page_size']);

        $list = $query_res->getCollection();
        
        // 获取当前登录用户（如果已登录）
        $current_user_id = null;
        try {
            $current_user = $this->auth->getUser();
            if (isset($current_user['id']) && $current_user['id']) {
                $current_user_id = $current_user['id'];
            }
        } catch (\Exception $e) {
            // 用户未登录，忽略
        }

        // 如果用户已登录，批量查询收藏状态
        $collected_teacher_detail_ids = [];
        if ($current_user_id) {
            // 收集所有teacher_detail_id
            $all_teacher_detail_ids = [];
            foreach ($list as $v) {
                foreach ($v['teacher_detail'] as $vv) {
                    if (isset($vv['id'])) {
                        $all_teacher_detail_ids[] = $vv['id'];
                    }
                }
            }
            // 批量查询收藏状态
            if (!empty($all_teacher_detail_ids)) {
                $collected_teacher_detail_ids = TeacherCollection::where(['user_id' => $current_user_id])
                    ->whereIn('teacher_detail_id', array_unique($all_teacher_detail_ids))
                    ->column('teacher_detail_id');
            }
        }
        
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = $v['user_id'];
            $arr[$k]['name']     = $v['name'];
            $club_dtl_name = [];
            $teacher_detail = [];
            foreach ($v['teacher_detail'] as $kk=>$vv){
                if(isset($vv['club_dtl_s']['name'])&&$vv['club_dtl_s']['name']){
                    $club_dtl_name[] = $vv['club_dtl_s']['name'];
                }
                $teacher_detail[$kk]['id'] = $vv['id'];
                $teacher_detail[$kk]['info_id'] = $vv['info_id'];
                $teacher_detail[$kk]['hourly_rate'] = $vv['hourly_rate'];
                $teacher_detail[$kk]['club_name'] = isset($vv['club_dtl_s']['name']) ? $vv['club_dtl_s']['name'] : '';
                $teacher_detail[$kk]['club_img_url'] = isset($vv['club_dtl_s']['img_url']) ? $vv['club_dtl_s']['img_url'] : '';
                $teacher_detail[$kk]['is_premium'] = $vv['is_premium'];
                $teacher_detail[$kk]['people'] = $vv['people'];
                if($vv['work_time']>0){
                    $teacher_detail[$kk]['work_time'] = $vv['work_time'].'年';
                }else{
                    $teacher_detail[$kk]['work_time'] = '';
                }
                // 检查该课程是否被收藏
                $is_collected = 2; // 默认2=未收藏
                if ($current_user_id && isset($vv['id']) && in_array($vv['id'], $collected_teacher_detail_ids)) {
                    $is_collected = 1; // 1=已收藏
                }
                $teacher_detail[$kk]['is_collected'] = $is_collected; // 1已收藏，2未收藏
            }
            $club_dtl_name = array_values(array_unique($club_dtl_name));
            $arr[$k]['club_dtl_name'] = $club_dtl_name;
            $arr[$k]['hourly_rate']    = $v['lowest_hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['main_score']);
            $arr[$k]['people']    = $v['main_people'];
            $arr[$k]['order_num']    = $v['order_num_all'];
            $arr[$k]['education_background']    = $v['education_background'];
            $week = isset($v['appointment_time_week']) ? $v['appointment_time_week'] : '';
            $time = isset($v['appointment_time']) ? $v['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $arr[$k]['avatar']    = $v['user']['avatar'];

            $area = $v['area'] ? explode(',',$v['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
            $arr[$k]['dtl']    = $teacher_detail;
        }

        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;
        $this->success('首页',$data);

        //教师
        $query_res = \app\admin\model\TeacherDetail::with(['identity','clubDtl']);
        if($club_id_str&&$club_dtl_id_str){
            $query_res = $query_res->where(" ((club_one_id in ({$club_id_str}) or club_two_id in ({$club_dtl_id_str})) or info_id in ({$identity_ids_str}))");
        }else{
            if($club_id_str){
                $query_res = $query_res->where("(club_one_id in ({$club_id_str}) or info_id in ({$identity_ids_str}))");
            }
            if($club_dtl_id_str){
                $query_res = $query_res->where("(club_two_id in ({$club_dtl_id_str}) or info_id in ({$identity_ids_str}))");
            }
            // 如果都没有，只查询name匹配的
            if(!$club_id_str && !$club_dtl_id_str){
                $query_res = $query_res->where("info_id in ({$identity_ids_str})");
            }
        }
//        $sql = $query_res->fetchSql(true)->select();

        $query_res = $query_res->order('order_num','desc')->paginate($params['page_size']);

        $list = $query_res->getCollection();
        
        // 获取当前登录用户（如果已登录）
        $current_user_id = null;
        try {
            $current_user = $this->auth->getUser();
            if (isset($current_user['id']) && $current_user['id']) {
                $current_user_id = $current_user['id'];
            }
        } catch (\Exception $e) {
            // 用户未登录，忽略
        }
        
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = isset($v['identity']['user_id']) ? $v['identity']['user_id'] : '';
            $arr[$k]['name']     = isset($v['identity']['name']) ? $v['identity']['name'] : '';
            $arr[$k]['club_dtl_name'] = isset($v['club_dtl']['name']) ? $v['club_dtl']['name'] : '';
            $arr[$k]['hourly_rate']    = $v['hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['score']);
            $arr[$k]['people']    = $v['people'];
            $arr[$k]['order_num']    = $v['order_num'];
            $arr[$k]['is_premium']    = $v['is_premium'];
            $week = isset($v['identity']['appointment_time_week']) ? $v['identity']['appointment_time_week'] : '';
            $time = isset($v['identity']['appointment_time']) ? $v['identity']['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $arr[$k]['avatar']    = isset($v['identity']['user']['avatar']) ? $v['identity']['user']['avatar'] : '';
            
            // 检查是否收藏：1已收藏，2未收藏
            $is_collected = 2; // 默认2=未收藏
            if ($current_user_id && isset($v['id'])) {
                $collection = TeacherCollection::where(['user_id' => $current_user_id, 'teacher_detail_id' => $v['id']])->find();
                if ($collection) {
                    $is_collected = 1;
                }
            }
            $arr[$k]['is_collected'] = $is_collected; // 1已收藏，2未收藏

            $area = $v['identity']['area'] ? explode(',',$v['identity']['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
        }
        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;

        $this->success('首页搜索结果',$data);
    }
    public function get_key_club_old(){
        $params = $this->request->param();
        if(!isset($params['keyword'])||!$params['keyword']){
            $this->error('缺少查询条件');
        }
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        $query_res = ClubDtl::where("name like '%{$params['keyword']}%'")->with(['clubs']);
        $query_res = $query_res->order('club_id','asc')->order('sort','desc')
            ->paginate($params['page_size']);

        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['club_id'] = $v['club_id'];
            $arr[$k]['club_name'] = isset($v['clubs']) ? $v['clubs']['club_name'] : '';
            $arr[$k]['club_img'] = isset($v['clubs']) ? isset($v['clubs']['club_img']) ? $v['clubs']['club_img'] : '' : '';
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['name'] = $v['name'] ? $v['name'] : '';
            $arr[$k]['img'] = $v['img_url'] ? $v['img_url'] : '';
        }
        $count = $query_res->total();

        $data = [];
        $data['list'] = $arr;
        $data['count'] = $count;

        $club_dtl_id = ClubDtl::where("name like '%{$params['keyword']}%'")->column('id');
        $club_id = Club::where("name like '%{$params['keyword']}%'")->column('id');

        $club_id_str = implode(',',$club_id);
        $club_dtl_id_str = implode(',',$club_dtl_id);
        //教师
        $query_res = \app\admin\model\IdentityInfo::with(['user','clubDtl'])->where(['identity_type'=>'教师']);
        if($club_id_str&&$club_dtl_id_str){
            $query_res = $query_res->where(" (club_one_id in ({$club_id_str}) or club_two_id in ({$club_dtl_id_str}))");
        }else{
            if($club_id_str){
                $query_res = $query_res->where("club_one_id in ({$club_id_str})");
            }
            if($club_dtl_id_str){
                $query_res = $query_res->where("club_two_id in ({$club_dtl_id_str})");
            }
        }
//        $sql = $query_res->fetchSql(true)->select();

        $query_res = $query_res->order('sort','desc')->paginate($params['page_size']);

        $list = $query_res->getCollection();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id']     = $v['id'];
            $arr[$k]['user_id'] = $v['user_id'];
            $arr[$k]['name']     = $v['name'];
            $arr[$k]['club_dtl_name'] = $v['club_dtl']['name'];
            $arr[$k]['hourly_rate']    = $v['hourly_rate'];
            $arr[$k]['score']    = $this->formatScore($v['score']);
            $arr[$k]['people']    = $v['people'];
            $arr[$k]['appointment_time_week']    = $v['appointment_time_week'].' '.$v['appointment_time'];
            $arr[$k]['avatar']    = $v['user']['avatar'];

            $area = $v['area'] ? explode(',',$v['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['tag_me'];
        }
        $count = $query_res->total();
        $data['teacher_list'] = $arr;
        $data['teacher_count'] = $count;

        $this->success('首页搜索结果',$data);
    }

    //后台提醒
    public function admin_tip(){
        $tx = Withdraw::where(['status'=>1])->count();
        $data = [];
        $data['txtip'] = $tx;
        $this->success('消息提醒',$data);
    }

    //学校名称搜索
    public function get_shool_name(){
        $params = $this->request->param();
        if(!isset($params['keyword'])||!$params['keyword']){
            $this->error('缺少查询条件');
        }
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }
        //此处搜索深圳的学校名称 然后返回
        $query_res = SearchShool::where("name like '%{$params['keyword']}%'")->order('id','desc')
            ->paginate($params['page_size']);

        $list = $query_res->getCollection();
        $count = $query_res->total();
        $data = [];
        $data['list'] = $list;
        $data['count'] = $count;
        $this->success('学校名称搜索',$data);
    }

    //客服
    public function customer_service(){
        $cs = CustomerService::order('id','asc')->select();
        $this->success('客服',$cs);
    }

    //发送即将上课消息
    public function send_sk(){
        $now = time();
        $future = $now + 600; // 10分钟内
        $todayDate = date('Y-m-d', $now);
        $weekMap = [
            1 => ['周一', '星期一'],
            2 => ['周二', '星期二'],
            3 => ['周三', '星期三'],
            4 => ['周四', '星期四'],
            5 => ['周五', '星期五'],
            6 => ['周六', '星期六'],
            7 => ['周日', '星期日', '周天', '星期天'],
        ];
        $todayWeeks = $weekMap[date('N', $now)];

        $records = TeacherClassDtl::alias('d')
            ->join('teacher_class c', 'd.teacher_class_id = c.id')
            ->join('user teacher', 'c.teacher_id = teacher.id','LEFT')
            ->join('user school', 'c.user_id = school.id','LEFT')
            ->where('d.status', 1)
            ->where('d.is_send_sj_notice', 1)
            ->where('c.status', 1)
            ->field('d.*, c.teacher_id, c.user_id, c.period_set, c.club_two_name, c.start_date, teacher.nickname AS teacher_name, school.nickname AS school_name')
            ->select();

        $noticeList = [];
        $updateIds = [];
        foreach ($records as $item) {
            $weekDate = trim($item['week_date'] ?? '');
            $timeStart = trim($item['time_start'] ?? '');
            if (!$timeStart) {
                continue;
            }

            $classDate = null;
            if ((int)$item['period_set'] === 2) {
                if ($weekDate !== $todayDate) {
                    continue;
                }
                $classDate = $weekDate;
            } else {
                if (!$weekDate) {
                    continue;
                }
                $matched = false;
                foreach ($todayWeeks as $name) {
                    if ($weekDate === $name) {
                        $matched = true;
                        break;
                    }
                }
                if (!$matched) {
                    continue;
                }
                if (!empty($item['start_date']) && strtotime($item['start_date']) > $now) {
                    continue;
                }
                $classDate = $todayDate;
            }

            $startTimestamp = strtotime($classDate . ' ' . $timeStart . ':00');
            if ($startTimestamp === false) {
                continue;
            }
            if ($startTimestamp < $now) {
                continue;
            }
            if ($startTimestamp > $future) {
                continue;
            }

            $updateIds[] = $item['id'];
            $startTimeStr = date('H:i', $startTimestamp);
            $clubName = $item['club_two_name'] ?: '课程';
            $teacherName = $item['teacher_name'] ?: '教师';
            $schoolName = $item['school_name'] ?: '校方';
            $nowStr = date('Y-m-d H:i:s', $now);

            $noticeList[] = [
                'title' => '课程即将开始提醒',
                'content' => $schoolName . "预约的课程「{$clubName}」将于{$startTimeStr}开始，请提前做好准备。",
                'need_confirm' => 2,
                'jump' => '课程详情',
                'teacher_class_id' => $item['teacher_class_id'],
                'teacher_class_dtl_id' => $item['id'],
                'send_user_id' => $item['user_id'],
                'get_user_id' => $item['teacher_id'],
                'identity_type' => '教师',
                'addtime' => $nowStr,
                'is_read' => 1,
                'class_num' => $item['class_num']
            ];

            $noticeList[] = [
                'title' => '课程即将开始提醒',
                'content' => $teacherName . "的课程「{$clubName}」将于{$startTimeStr}开始，请提前做好准备。",
                'need_confirm' => 2,
                'jump' => '课程详情',
                'teacher_class_id' => $item['teacher_class_id'],
                'teacher_class_dtl_id' => $item['id'],
                'send_user_id' => $item['teacher_id'],
                'get_user_id' => $item['user_id'],
                'identity_type' => '校方',
                'addtime' => $nowStr,
                'is_read' => 1,
                'class_num' => $item['class_num']
            ];
        }
        if ($noticeList) {
            Notice::insertAll($noticeList);
            // 发送个推消息
            foreach ($noticeList as $notice) {
                Notice::sendGetuiPush($notice);
            }
        }
        if ($updateIds) {
            $updateIds = array_unique($updateIds);
            TeacherClassDtl::whereIn('id', $updateIds)->update(['is_send_sj_notice' => 2]);
        }

        // 个推消息已在 insertAll 后统一发送，此处删除重复代码
        $this->success('执行完成', ['count' => count($updateIds)]);
    }

    //测试推送
    public function test_gt(){
        $params = $this->request->param();
        if(!isset($params['cid'])||!$params['cid']){
            $this->error('缺少cid');
        }
        if(!isset($params['title'])||!$params['title']){
            $this->error('缺少title');
        }
        if(!isset($params['content'])||!$params['content']){
            $this->error('缺少content');
        }

        $cid = $params['cid'];
        $title = $params['title'];
        $content = $params['content'];

        if (empty($cid)) {
            $this->error('cid不能为空');
        }

        $getui = new Getui();

        $harmonyConfig = [
            'notification' => [
                'title' => $title,
                'body'  => $content,
                'click_type' => 'payload_custom',
                'category'=>'MARKETING',
                'payload'=>'pages/message/message',
            ],
        ];

        // 构建小米通道配置（小米使用Android厂商通道，厂商代码为XM）
        $androidConfig = [
            'ups' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'payload_custom',
                    'payload'=>'pages/message/message',
                ],
            ],
        ];

        // 构建推送参数
        $payload = [
            'request_id' => uniqid('xiaomi_', true),
            'audience' => ['cid' => [$cid]],
            'settings' => [
                'ttl' => 7200000, // 消息有效期（毫秒），默认2小时
                'strategy' => [
                    'default' => 1,
                ],
            ],
            'push_message' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'payload_custom',
                    'payload' => 'pages/message/message',
                ]
            ],
            'push_channel' => [
                'android' => $androidConfig,
                'harmony' => $harmonyConfig,
            ],
        ];
        $result = $getui->pushToSingle($payload);
        $this->success('推送成功', $result);
        exit;


        try {
            $getui = new Getui();
            $payload = $this->buildGetuiPayload($params['cid'], $params['title'], $params['content']);
            $res = $getui->pushToSingle($payload);
            $this->success('完成',$res);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    protected function formatScore($score)
    {
        if ($score === null || $score === '') {
            return $score;
        }
        if (is_numeric($score)) {
            $score = (float)$score;
            
            // 最简单最傻瓜式的判断
            // 小于等于0 -> 0
            if ($score <= 0) {
                return '0.0';
            }
            
            // 大于等于10 -> 5
            if ($score >= 10) {
                return '5.0';
            }
            
            // 其他情况：向下取整得到整数部分
            $intPart = (int)floor($score);
            
            // 判断是否为整数（分数的小数部分是否接近0）
            $isInteger = abs($score - $intPart) < 0.001;
            
//            if ($isInteger) {
//                // 整数：n * 0.5
//                // 1 -> 0.5, 2 -> 1.0, 3 -> 1.5, 4 -> 2.0, ...
                $formattedScore = $intPart * 0.5;
//            } else {
//                // 小数：(n+1) * 0.5
//                // 0.1-0.9 -> 0.5, 1.1-1.9 -> 1.0, 2.1-2.9 -> 1.5, ...
//                $formattedScore = ($intPart + 1) * 0.5;
//            }
            
            return number_format($formattedScore, 1, '.', '');
        }
        return $score;
    }

    protected function buildGetuiPayloadSs($cid, $title, $content)
    {
        return [
            'request_id' => uniqid(),
            'audience' => ['cid' => [$cid]],
            'push_message' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                ],
            ],
            'push_channel' => [
                'ios' => [
                    'type' => 'apns',
                    'payload' => [
                        'aps' => [
                            'alert' => [
                                'title' => $title,
                                'body'  => $content,
                            ],
                            'sound' => 'default',
                        ],
                    ],
                ],
            ],
        ];
    }


    protected function buildGetuiPayload($cid, $title, $content)
    {
        $harmonyConfig = [
            'notification' => [
                'title' => $title,
                'body'  => $content,
                'click_type' => 'payload_custom',
                'category'=>'MARKETING',
                'payload'=>'pages/message/message',
            ],
        ];

        $androidConfig = [
            'ups' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'payload_custom',
                    'payload'=>'pages/message/message',
                ],
            ],
        ];

        // 构建推送参数
        return [
            'request_id' => uniqid(),
            'audience' => ['cid' => [$cid]],
            'settings' => [
                'ttl' => 7200000, // 消息有效期（毫秒），默认2小时
                'strategy' => [
                    'default' => 1,
                ],
            ],
            'push_message' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'payload_custom',
                    'payload' => 'pages/message/message',
                ]
            ],
            'push_channel' => [
                'android' => $androidConfig,
                'harmony' => $harmonyConfig,
            ],
        ];

        exit;
        $result = $getui->pushToSingle($payload);
        $this->success('推送成功', $result);

        $intent = "intent://com.xwx.sdb/message?#Intent;scheme=sdbschema;launchFlags=0x04000000;package=com.xwx.sdb;component=com.xwx.sdb%2Fcom.xwx.sdb.pages%2Fmessage%2Fmessage;S.gttask=;end";
        $path = 'pages/message/message'; // 统一的跳转路径

        return [
            'request_id' => uniqid(),
            'audience' => ['cid' => [$cid]],
            'settings' => [
                'ttl' => 7200000, // 消息有效期（毫秒），默认2小时
                'strategy' => [
                    'default' => 1, // 默认策略：1-个推通道优先，2-厂商通道优先
                    'st' => 4, // 华为鸿蒙通道策略：4-仅走厂商通道
                ],
            ],
            'push_message' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'intent',
                    'intent' => $intent,
                ]
            ],
            'push_channel' => [
                'harmony' => [
                    'notification' => [
                        'title' => $title,
                        'body'  => $content,
                        'category' => 'MARKETING', // 通知类别：MARKETING、SERVICE、SOCIAL、SYSTEM
                        'click_type' => 'payload_custom', // 点击类型：startapp(打开应用)、payload_custom(自定义消息)、url(打开网页)
                        'payload' => json_encode(['path' => $path, 'intent' => $intent], JSON_UNESCAPED_UNICODE), // 传递跳转路径和intent信息
                    ],
                ],
            ],
        ];
    }

    public function get_gt(){
        $params = $this->request->param();
        $taskId = $params['taskId'];
        $getui = new Getui();

        // 单个taskId
        $result = $getui->getPushReport($taskId);

        var_dump($result);
    }

    public function push_all_gt(){
        $getui = new Getui();

        // 构建推送参数
        $params = [
            'request_id' => uniqid('push_', true), // 10-32位的请求ID
            'group_name' => '系统通知', // 可选，任务组名
            'settings' => [
                'ttl' => 7200000, // 消息有效期（毫秒），默认2小时
            ],
            'push_message' => [
                'notification' => [
                    'title' => '通知标题',
                    'body'  => '通知内容',
                    'click_type' => 'url',
                    'url' => 'https://example.com',
                ],
            ],
            // 可选：厂商通道配置
            'push_channel' => [
                'harmony' => [
                    'notification' => [
                        'title' => '鸿蒙通知标题',
                        'body'  => '鸿蒙通知内容',
                        'category' => 'MARKETING',
                        'click_type' => 'startapp',
                    ],
                ],
            ],
        ];

// 执行全量推送
        $result = $getui->pushToApp($params);
        var_dump($result);
        exit;
    }

    public function get_cid_user(){
        $params = $this->request->param();
        $cid = $params['cid'];
        $getui = new Getui();

        $result = $getui->getUserBaseInfo($cid);
        var_dump($result);
    }

    /**
     * 给华为HarmonyOS设备推送通知（支持华为手机和平板，如MatePad Air）
     * @param string $cid 用户cid
     * @param string $title 推送标题
     * @param string $content 推送内容
     * @param string $category 通知类别：MARKETING(营销)、SERVICE(服务)、SOCIAL(社交)、SYSTEM(系统)，默认MARKETING
     * @param string $clickType 点击类型：startapp(打开应用)、url(打开网页)、payload_custom(自定义消息，用于打开应用内指定页面)，默认startapp
     * @param string $intent Intent字符串，当clickType为payload_custom时，会在payload中传递此intent
     * @param string $url URL地址，当clickType为url时使用
     * @param array $customPayload 自定义payload数据，当clickType为payload_custom时使用，如果不提供则使用默认的path和intent
     */
    public function pushToHarmony($cid = '', $title = '', $content = '', $category = 'MARKETING', $clickType = 'startapp', $intent = '', $url = '', $customPayload = [])
    {
        $params = $this->request->param();
        $cid = $cid ?: ($params['cid'] ?? '');
        $title = $title ?: ($params['title'] ?? '通知标题');
        $content = $content ?: ($params['content'] ?? '通知内容');
        $category = $params['category'] ?? $category;
        $clickType = $params['click_type'] ?? $clickType;
        $intent = $intent ?: ($params['intent'] ?? '');
        $url = $url ?: ($params['url'] ?? '');
        
        if (empty($cid)) {
            $this->error('cid不能为空');
        }
        
        $getui = new Getui();
        
        // 默认Intent（如果未提供）
        if (empty($intent)) {
            $intent = "intent://com.xwx.sdb/message?#Intent;scheme=sdbschema;launchFlags=0x04000000;package=com.xwx.sdb;component=com.xwx.sdb%2Fcom.xwx.sdb.pages%2Fmessage%2Fmessage;S.gttask=;end";
        }
        
        $path = 'pages/message/message';
        
        // 构建harmony通道配置
        // 注意：harmony通道的click_type支持：url、want、payload、payload_custom、none、startapp
        // 如果要打开应用内指定页面，使用payload_custom，在payload中传递intent
        $harmonyConfig = [
            'notification' => [
                'title' => $title,
                'body'  => $content,
                'category' => $category,
            ],
        ];
        
        // 根据clickType设置相应参数
        if ($clickType === 'url') {
            $harmonyConfig['notification']['click_type'] = 'url';
            $harmonyConfig['notification']['url'] = $url ?: 'https://www.example.com';
        } elseif ($clickType === 'payload_custom') {
            // 自定义payload（用于打开应用内指定页面）
            $harmonyConfig['notification']['click_type'] = 'payload_custom';
            $payloadData = !empty($customPayload) ? $customPayload : ['path' => $path, 'intent' => $intent];
            $harmonyConfig['notification']['payload'] = json_encode($payloadData, JSON_UNESCAPED_UNICODE);
        } else {
            // 默认使用startapp（打开应用）
            $harmonyConfig['notification']['click_type'] = 'startapp';
        }
        
        // 构建推送参数
        $payload = [
            'request_id' => uniqid('harmony_', true),
            'audience' => ['cid' => [$cid]],
            'settings' => [
                'ttl' => 7200000, // 消息有效期（毫秒），默认2小时
                'strategy' => [
                    'default' => 2, // 2-厂商通道优先
                    'st' => 4, // 4-仅走厂商通道（华为通道）
                ],
            ],
            'push_message' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'intent',
                    'intent' => $intent,
                ]
            ],
            'push_channel' => [
                'android' => [
                    'ups' => [
                        'notification' => [
                            'title' => $title,
                            'body'  => $content,
                            'click_type' => 'intent',
                            'intent' => $intent,
                        ],
                    ],
                ],
                'harmony' => $harmonyConfig,
            ],
        ];
        
        try {
            $result = $getui->pushToSingle($payload);
            $this->success('推送成功', [
                'result' => $result,
                'device_type' => '华为HarmonyOS设备（支持手机和平板）',
                'push_channel' => 'harmony',
                'config' => [
                    'category' => $category,
                    'click_type' => $clickType,
                ],
            ]);
        } catch (\Exception $e) {
            $this->error('推送失败：' . $e->getMessage());
        }
    }

    /**
     * 给小米手机推送离线下发消息
     * @param string $cid 用户cid
     * @param string $title 推送标题
     * @param string $content 推送内容
     * @param string $clickType 点击类型：startapp(打开应用)、intent(打开应用内指定页面)、url(打开网页)，默认startapp
     * @param string $intent Intent字符串，当clickType为intent时使用
     * @param string $url URL地址，当clickType为url时使用
     * @param string $channelId 小米渠道ID，如果未提供则从配置中获取
     */
    public function pushToXiaomi($cid = '', $title = '', $content = '', $clickType = 'startapp', $intent = '', $url = '', $channelId = '')
    {
        $params = $this->request->param();
        $cid = $cid ?: ($params['cid'] ?? '');
        $title = $title ?: ($params['title'] ?? '接口离线测试2');
        $content = $content ?: ($params['content'] ?? '接口离线测试内容2');
        $clickType = $params['click_type'] ?? $clickType;
        $intent = $intent ?: ($params['intent'] ?? '');
        $url = $url ?: ($params['url'] ?? '');
        $channelId = $channelId ?: ($params['channel_id'] ?? '');
        
        if (empty($cid)) {
            $this->error('cid不能为空');
        }
        
        $getui = new Getui();

        $harmonyConfig = [
            'notification' => [
                'title' => $title,
                'body'  => $content,
                'click_type' => 'payload_custom',
                'category'=>'MARKETING',
                'payload'=>'pages/message/message',
            ],
        ];



        // 构建小米通道配置（小米使用Android厂商通道，厂商代码为XM）
        $androidConfig = [
            'ups' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'payload_custom',
                    'payload'=>'pages/message/message',
                ],
            ],
        ];

        // 构建推送参数
        $payload = [
            'request_id' => uniqid('xiaomi_', true),
            'audience' => ['cid' => [$cid]],
            'settings' => [
                'ttl' => 7200000, // 消息有效期（毫秒），默认2小时
                'strategy' => [
                    'default' => 1, // 2-厂商通道优先
                ],
            ],
            'push_message' => [
                'notification' => [
                    'title' => $title,
                    'body'  => $content,
                    'click_type' => 'payload_custom',
                    'payload' => 'pages/message/message',
                ]
            ],
            'push_channel' => [
                'android' => $androidConfig,
                'harmony' => $harmonyConfig,
            ],
        ];
        
        try {
            $result = $getui->pushToSingle($payload);
            $this->success('推送成功', [
                'result' => $result,
                'device_type' => '小米手机',
                'push_channel' => 'android (小米厂商通道-离线下发)',
                'config' => [
                    'click_type' => $clickType,
                    'channel_id' => $androidConfig['ups']['options']['XM']['/extra.channel_id'] ?? '',
                ],
            ]);
        } catch (\Exception $e) {
            $this->error('推送失败：' . $e->getMessage());
        }
    }

    public function hw_callback(){
        $all = $this->request->param();
        $add = [];
        $add['name'] = '华为消息推送回调';
        $add['content'] = json_encode($all);
        WlqTest::create($add);
        return json(['code'=>"0",'message'=>'success']);
    }
}
